const Response = require('@/utils/response');
const LinkService = require('@/service/link');
const {uploadToQiniu} = require('@/utils/qiniuUpload');

class LinkController {
  async getLinks(ctx) {
    const params = ctx.request.body;
    // console.log(params, 'params');
    const data = await LinkService.getLinks(params);
    return Response.success(ctx, data, '获取链接成功');
  }

  async getAllLinks(ctx) {
    const data = await LinkService.getAllLinks();
    return Response.success(ctx, data, '获取所有链接成功');
  }

  async getCategoryWithLinks(ctx) {
    const data = await LinkService.getCategoryWithLinks();
    return Response.success(ctx, data, '获取分类及链接成功');
  }

  async saveLink(ctx) {
    const params = ctx.request.body;
    if (!title || !category_id) {
      return Response.error(ctx, '缺少必要参数', 400);
    }
    const file = ctx.request.files?.icon_url;
    let icon_url = params.icon_url || '';
    if(file) {
      icon_url = await uploadToQiniu(file);
    }

    const user_id = ctx.state.user.id;
    const res = await LinkService.saveLink({...params, icon_url, user_id});
    return Response.success(ctx, res, '添加链接成功');
  }

  async deleteLink(ctx) {
    const { id } = ctx.request.body;
    if (!id) return Response.error(ctx, '链接ID不能为空', 400);
    const res = await LinkService.deleteLink(id);
    return Response.success(ctx, res, '删除链接成功');
  }
}

module.exports = new LinkController();